<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>证书模板设计</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
      </div>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
              <span>模板信息</span>
            </div>
            <el-form ref="form" :model="templateInfo" :rules="rules" label-width="80px" size="small">
              <el-form-item label="模板名称" prop="name">
                <el-input v-model="templateInfo.name" placeholder="请输入模板名称" />
              </el-form-item>
              <el-form-item label="模板类型" prop="type">
                <el-select v-model="templateInfo.type" placeholder="请选择模板类型" style="width: 100%;">
                  <el-option
                    v-for="dict in dict.type.certificate_template_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="templateInfo.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="saveTemplate" :loading="saveLoading">保存模板</el-button>
              </el-form-item>
            </el-form>

            <div class="components-list">
              <div class="components-title">组件列表</div>
              <draggable
                class="dragArea list-group"
                :list="templateComponents"
                :group="{ name: 'components', pull: 'clone', put: false }"
                :clone="cloneComponent"
                @start="dragStart"
                @end="dragEnd"
              >
                <div
                  class="list-group-item"
                  v-for="(element, index) in templateComponents"
                  :key="index"
                >
                  <i :class="element.icon"></i> {{ element.label }}
                </div>
              </draggable>
            </div>

            <div class="variables-list">
              <div class="variables-title">
                <span>变量列表</span>
                <el-button type="text" size="mini" @click="addVariable">添加变量</el-button>
              </div>
              <el-table :data="variables" size="mini" border>
                <el-table-column prop="name" label="变量名" width="120"></el-table-column>
                <el-table-column prop="description" label="描述"></el-table-column>
                <el-table-column label="操作" width="80" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="insertVariable(scope.row)">插入</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
              <span>模板设计区</span>
              <div style="float: right;">
                <el-button size="mini" type="primary" @click="previewTemplate">预览</el-button>
                <el-button size="mini" type="success" @click="saveTemplate">保存</el-button>
              </div>
            </div>
            <div class="editor-container">
              <div class="editor-toolbar">
                <el-button-group>
                  <el-button size="mini" @click="execCommand('bold')"><i class="el-icon-bold"></i></el-button>
                  <el-button size="mini" @click="execCommand('italic')"><i class="el-icon-italic"></i></el-button>
                  <el-button size="mini" @click="execCommand('underline')"><i class="el-icon-underline"></i></el-button>
                </el-button-group>
                <el-button-group style="margin-left: 10px;">
                  <el-button size="mini" @click="execCommand('justifyLeft')"><i class="el-icon-align-left"></i></el-button>
                  <el-button size="mini" @click="execCommand('justifyCenter')"><i class="el-icon-align-center"></i></el-button>
                  <el-button size="mini" @click="execCommand('justifyRight')"><i class="el-icon-align-right"></i></el-button>
                </el-button-group>
                <el-button-group style="margin-left: 10px;">
                  <el-button size="mini" @click="execCommand('insertOrderedList')"><i class="el-icon-list-ol"></i></el-button>
                  <el-button size="mini" @click="execCommand('insertUnorderedList')"><i class="el-icon-list-ul"></i></el-button>
                </el-button-group>
                <el-color-picker size="mini" v-model="textColor" @change="changeTextColor" style="margin-left: 10px;"></el-color-picker>
                <el-select size="mini" v-model="fontSize" @change="changeFontSize" style="width: 100px; margin-left: 10px;">
                  <el-option v-for="size in fontSizes" :key="size" :label="size + 'px'" :value="size"></el-option>
                </el-select>
              </div>
              <div class="editor-content" contenteditable="true" ref="editor" @input="onEditorChange"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 预览模板对话框 -->
      <el-dialog title="预览证书模板" :visible.sync="previewVisible" width="800px" append-to-body>
        <div v-html="templateContent" class="template-preview"></div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="previewVisible = false">关 闭</el-button>
        </div>
      </el-dialog>

      <!-- 添加变量对话框 -->
      <el-dialog title="添加变量" :visible.sync="variableDialogVisible" width="500px" append-to-body>
        <el-form ref="variableForm" :model="variableForm" :rules="variableRules" label-width="80px">
          <el-form-item label="变量名" prop="name">
            <el-input v-model="variableForm.name" placeholder="请输入变量名（英文）"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="variableForm.description" placeholder="请输入变量描述"></el-input>
          </el-form-item>
          <el-form-item label="默认值">
            <el-input v-model="variableForm.defaultValue" placeholder="请输入默认值"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="variableDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitVariableForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import draggable from 'vuedraggable';
import { getTemplate, updateTemplate, listTemplateVariables, saveTemplateVariables, previewTemplate } from "@/api/certificate/template";

export default {
  name: "TemplateMaintain",
  components: {
    draggable
  },
  dicts: ['certificate_template_type'],
  data() {
    return {
      // 模板ID
      templateId: null,
      // 模板信息
      templateInfo: {
        id: null,
        name: '',
        type: '',
        content: '',
        remark: ''
      },
      // 模板内容
      templateContent: '',
      // 保存加载状态
      saveLoading: false,
      // 预览对话框
      previewVisible: false,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "模板类型不能为空", trigger: "change" }
        ]
      },
      // 可拖拽组件列表
      templateComponents: [
        { label: '标题', type: 'title', icon: 'el-icon-s-comment' },
        { label: '表格', type: 'table', icon: 'el-icon-s-grid' },
        { label: '图片', type: 'image', icon: 'el-icon-picture' },
        { label: '签名', type: 'signature', icon: 'el-icon-edit' },
        { label: '分隔线', type: 'divider', icon: 'el-icon-minus' },
        { label: '段落', type: 'paragraph', icon: 'el-icon-document' }
      ],
      // 变量列表
      variables: [],
      // 变量对话框
      variableDialogVisible: false,
      variableForm: {
        name: '',
        description: '',
        defaultValue: ''
      },
      variableRules: {
        name: [
          { required: true, message: '变量名不能为空', trigger: 'blur' },
          { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '变量名只能包含字母、数字和下划线，且必须以字母开头', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '变量描述不能为空', trigger: 'blur' }
        ]
      },
      // 文本编辑器相关
      textColor: '#000000',
      fontSize: 14,
      fontSizes: [10, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48]
    };
  },
  created() {
    this.templateId = this.$route.query.id;
    if (this.templateId) {
      this.getTemplateInfo();
      this.getTemplateVariables();
    }
  },
  mounted() {
    // 初始化编辑器内容
    if (this.templateInfo.content) {
      this.$refs.editor.innerHTML = this.templateInfo.content;
    }
  },
  methods: {
    // 获取模板信息
    getTemplateInfo() {
      getTemplate(this.templateId).then(response => {
        this.templateInfo = response.data;
        if (this.templateInfo.content && this.$refs.editor) {
          this.$refs.editor.innerHTML = this.templateInfo.content;
        }
      });
    },
    // 获取模板变量
    getTemplateVariables() {
      listTemplateVariables(this.templateId).then(response => {
        this.variables = response.data || [];
      });
    },
    // 返回列表
    goBack() {
      this.$router.push('/certificate/template');
    },
    // 保存模板
    saveTemplate() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.saveLoading = true;
          // 获取编辑器内容
          if (this.$refs.editor) {
            this.templateInfo.content = this.$refs.editor.innerHTML;
          }
          
          updateTemplate(this.templateInfo).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.saveLoading = false;
            // 如果是新建模板，保存后跳转到编辑页面
            if (!this.templateId) {
              this.templateId = response.data;
              this.$router.replace({ path: '/certificate/template/maintain', query: { id: this.templateId } });
            }
          }).catch(() => {
            this.saveLoading = false;
          });
        }
      });
    },
    // 预览模板
    previewTemplate() {
      if (this.templateId) {
        previewTemplate(this.templateId).then(response => {
          this.templateContent = response.data;
          this.previewVisible = true;
        });
      } else {
        // 如果是新模板，直接预览当前编辑器内容
        if (this.$refs.editor) {
          this.templateContent = this.$refs.editor.innerHTML;
          this.previewVisible = true;
        }
      }
    },
    // 克隆组件
    cloneComponent(item) {
      return { ...item };
    },
    // 拖拽开始
    dragStart(evt) {
      console.log('拖拽开始', evt);
    },
    // 拖拽结束
    dragEnd(evt) {
      console.log('拖拽结束', evt);
      const component = this.templateComponents[evt.oldIndex];
      this.insertComponent(component);
    },
    // 插入组件
    insertComponent(component) {
      let html = '';
      switch (component.type) {
        case 'title':
          html = '<h2 style="text-align:center;">证书标题</h2>';
          break;
        case 'table':
          html = '<table border="1" style="width:100%;border-collapse:collapse;"><tr><th>列1</th><th>列2</th><th>列3</th></tr><tr><td>数据1</td><td>数据2</td><td>数据3</td></tr></table>';
          break;
        case 'image':
          html = '<div style="text-align:center;"><img src="https://via.placeholder.com/150" alt="图片" style="max-width:100%;"></div>';
          break;
        case 'signature':
          html = '<div style="margin-top:20px;text-align:right;"><p>签发人: ____________</p><p>日期: {{date}}</p></div>';
          break;
        case 'divider':
          html = '<hr style="border:none;border-top:1px solid #ddd;margin:20px 0;">';
          break;
        case 'paragraph':
          html = '<p>在此输入段落内容...</p>';
          break;
      }
      
      if (this.$refs.editor) {
        // 获取选中的范围
        const selection = window.getSelection();
        const range = selection.getRangeAt(0);
        
        // 创建一个文档片段
        const fragment = document.createRange().createContextualFragment(html);
        
        // 插入文档片段
        range.deleteContents();
        range.insertNode(fragment);
        
        // 更新模板内容
        this.templateInfo.content = this.$refs.editor.innerHTML;
      }
    },
    // 添加变量对话框
    addVariable() {
      this.variableForm = {
        name: '',
        description: '',
        defaultValue: ''
      };
      this.variableDialogVisible = true;
    },
    // 提交变量表单
    submitVariableForm() {
      this.$refs.variableForm.validate(valid => {
        if (valid) {
          // 检查变量名是否重复
          const exists = this.variables.some(v => v.name === this.variableForm.name);
          if (exists) {
            this.$message.error('变量名已存在');
            return;
          }
          
          this.variables.push({
            name: this.variableForm.name,
            description: this.variableForm.description,
            defaultValue: this.variableForm.defaultValue
          });
          
          // 如果模板ID存在，保存变量到服务器
          if (this.templateId) {
            saveTemplateVariables({
              templateId: this.templateId,
              variables: this.variables
            }).then(() => {
              this.$message.success('变量添加成功');
            });
          }
          
          this.variableDialogVisible = false;
        }
      });
    },
    // 插入变量
    insertVariable(variable) {
      if (this.$refs.editor) {
        const varTag = `{{${variable.name}}}`;
        
        // 获取选中的范围
        const selection = window.getSelection();
        const range = selection.getRangeAt(0);
        
        // 创建文本节点
        const textNode = document.createTextNode(varTag);
        
        // 插入文本节点
        range.deleteContents();
        range.insertNode(textNode);
        
        // 更新模板内容
        this.templateInfo.content = this.$refs.editor.innerHTML;
      }
    },
    // 执行编辑器命令
    execCommand(command, value = null) {
      document.execCommand(command, false, value);
      // 更新模板内容
      if (this.$refs.editor) {
        this.templateInfo.content = this.$refs.editor.innerHTML;
      }
    },
    // 修改文本颜色
    changeTextColor(color) {
      this.execCommand('foreColor', color);
    },
    // 修改字体大小
    changeFontSize(size) {
      this.execCommand('fontSize', size / 4); // 浏览器fontSize命令使用1-7的值
    },
    // 编辑器内容变化
    onEditorChange() {
      if (this.$refs.editor) {
        this.templateInfo.content = this.$refs.editor.innerHTML;
      }
    }
  }
};
</script>

<style scoped>
.components-list {
  margin-top: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.components-title {
  padding: 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  font-weight: bold;
}
.list-group-item {
  padding: 10px;
  border-bottom: 1px solid #dcdfe6;
  cursor: move;
}
.list-group-item:last-child {
  border-bottom: none;
}
.list-group-item i {
  margin-right: 5px;
}
.variables-list {
  margin-top: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.variables-title {
  padding: 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.editor-toolbar {
  padding: 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
}
.editor-content {
  min-height: 500px;
  padding: 15px;
  outline: none;
  background-color: white;
}
.template-preview {
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 300px;
  max-height: 500px;
  overflow-y: auto;
}
</style> 